/**
 * 级联地址选择功能
 * on 2020.02.27
 * add by lifenping
 */

import { Cascader, Form, message } from 'antd';
import React, { Component } from 'react';
import { getChildList, getProvinceList } from './service';

const FormItem = Form.Item;

interface PropsType {
  form?: any;
  name: string;
  getFieldDecorator: any;
  label?: string;
  initialValue?: any[];
  placeholder: string;
  labelCol?: any;
  wrapperCol?: any;
  disabled?: boolean;
  allowEmpty?: boolean;
}
interface StateType {
  addressList: optionParams[];
}

// 省市相关ts参数
interface optionParams {
  label?: string;
  value?: string;
  isLeaf?: boolean;
  children?: any;
}

interface apiParams {
  name?: string;
  pid?: string;
  id?: string;
}

class AddressCascader extends Component<PropsType, StateType> {
  lock = false;

  static defaultProps = {
    label: '选择地址',
    initialValue: [],
    placeholder: '请选择',
    labelCol: {},
    wrapperCol: {},
    disabled: false,
  };

  constructor(props: PropsType) {
    super(props);
    this.state = {
      addressList: [],
    };
  }

  componentDidMount() {
    this.getProvince();
  }

  /* *
   * 获取所有的省列表
   */
  getProvince = () =>
    getProvinceList().then(res => {
      const list: optionParams[] = [];
      if (res.code === 0) {
        const { initialValue } = this.props;
        console.log(initialValue)
        res.data.map((item: apiParams) => {
          const newItem = Object.assign({
            label: item.name,
            value: item.id,
            isLeaf: false,
          });
          list.push(newItem);
          // 如果初始化时initialValue有值，则自动调loadData接口
          if (initialValue && initialValue.length > 0) {
            this.lock = false;
            if (item.id === initialValue[0]) {
              this.loadData([newItem]);
            }
          }
          return true;
        });
        this.setState({
          addressList: list,
        });
      } else {
        message.error(res.err);
      }
    });

  // 获取市
  loadData = (selectedOptions: any) => {
    console.log(selectedOptions);
    // 点击省和市都调getChildList接口
    const targetOption = selectedOptions.length === 1 ? selectedOptions[0] : selectedOptions[1];
    return getChildList({
      pid: targetOption.value,
    }).then(res => {
      const list: optionParams[] = [];
      if (res.code === 0) {
        res.data.map((item: apiParams) => {
          list.push({
            label: item.name,
            value: item.id,
            isLeaf: selectedOptions.length === 2,
          });
          return true;
        });
        targetOption.children = list;
        this.setState(state => ({
          addressList: state.addressList,
        }));
        // 如果initialValue存在，则自动调市接口，获取区列表
        const { initialValue } = this.props;
        if (initialValue && initialValue[1] && !this.lock) {
          for (let i = 0; i < list.length + 1; i++) {
            if (list[i].value === initialValue[1]) {
              selectedOptions.push(list[i]);
              this.lock = true;
              break;
            }
          }
          this.loadData(selectedOptions);
        }
      } else {
        message.error(res.err);
      }
    });
  };

  render() {
    const { addressList } = this.state;
    const {
      getFieldDecorator,
      name,
      label,
      initialValue = [],
      placeholder,
      wrapperCol,
      labelCol,
      disabled,
      allowEmpty,
    } = this.props;
    const initVal =
      initialValue && initialValue.length ? initialValue.map(item => Number(item)) : null;
    const formCol = labelCol.span ? { labelCol, wrapperCol } : {};
    return (
      <FormItem label={label} {...formCol}>
        {getFieldDecorator(name, {
          initialValue: initVal,
          rules: [{ required: !allowEmpty, message: '请选择' }],
        })(
          <Cascader
            options={addressList}
            loadData={this.loadData}
            placeholder={placeholder}
            disabled={disabled}
          />,
        )}
      </FormItem>
    );
  }
}
export default AddressCascader;
